package com.cookapp.service;

import com.cookapp.common.exception.BusinessException;
import com.cookapp.common.enums.ResultCode;
import com.cookapp.model.dto.UserDTO;
import com.cookapp.model.entity.User;
import com.cookapp.model.vo.UserVO;
import com.cookapp.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    /**
     * 根据ID获取用户
     */
    public User getById(Long id) {
        return userRepository.findById(id);
    }

    /**
     * 根据openId获取用户
     */
    public User getByOpenId(String openId) {
        return userRepository.findByOpenId(openId);
    }

    /**
     * 创建用户
     */
    @Transactional(rollbackFor = Exception.class)
    public void createUser(User user) {
        userRepository.insert(user);
    }

    /**
     * 更新用户信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(User user) {
        userRepository.update(user);
    }

    /**
     * 获取用户信息
     */
    public UserVO getUserInfo(Long userId) {
        User user = userRepository.findById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 更新用户信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(Long userId, UserDTO userDTO) {
        User user = userRepository.findById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        
        // 更新用户信息
        user.setNickname(userDTO.getNickname());
        user.setAvatar(userDTO.getAvatar());
        user.setGender(userDTO.getGender());
        user.setPhone(userDTO.getPhone());
        user.setEmail(userDTO.getEmail());
        user.setUpdateTime(LocalDateTime.now());
        
        userRepository.update(user);
    }

    /**
     * 上传用户头像
     */
    @Transactional(rollbackFor = Exception.class)
    public void uploadAvatar(Long userId, String avatarUrl) {
        User user = userRepository.findById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        
        user.setAvatar(avatarUrl);
        user.setUpdateTime(LocalDateTime.now());
        
        userRepository.update(user);
    }

    /**
     * 根据手机号获取用户
     */
    public User getByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }
    
    /**
     * 手机号验证码登录
     */
    @Transactional(rollbackFor = Exception.class)
    public User loginByPhone(String phone, String nickname, String avatar, Integer gender) {
        User user = getByPhone(phone);
        if (user == null) {
            // 新用户，创建用户
            user = new User();
            user.setPhone(phone);
            user.setNickname(nickname != null ? nickname : "用户" + phone.substring(phone.length() - 4));
            user.setAvatar(avatar);
            user.setGender(gender != null ? gender : 0);
            user.setStatus(1);
            user.setLastLoginTime(LocalDateTime.now());
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setDeleted(0);
            
            createUser(user);
        } else {
            // 更新登录时间
            user.setLastLoginTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            
            // 如果提供了昵称、头像等信息，则更新
            if (nickname != null) {
                user.setNickname(nickname);
            }
            if (avatar != null) {
                user.setAvatar(avatar);
            }
            if (gender != null) {
                user.setGender(gender);
            }
            
            updateUser(user);
        }
        
        return user;
    }
} 